// 定义组合式API仓库
import { defineStore } from 'pinia'
import { getPrefixName } from '@/config'
import { getDictItemList } from '@/api/system/dictItem'
import type { ItemFormInt } from '@/api/system/dictItem/types'

/**
 * 缓存字典
 */
export default defineStore(getPrefixName('dict'), () => {
  const dictCache = ref<Record<string, ItemFormInt[]>>({})

  // 请求队列（防止重复请求）
  const requestQueue: Record<string, Promise<void>> = {}

  /**
   * 缓存字典数据
   * @param dictCode 字典编码
   * @param data 字典项列表
   */
  const cacheDictItems = (dictCode: string, data: ItemFormInt[]) => {
    dictCache.value[dictCode] = data
  }

  /**
   * 加载字典数据（如果缓存中没有则请求）
   * @param dictCode 字典编码
   */
  const loadDictItems = async (dictCode: string) => {
    if (dictCache.value[dictCode] && dictCache.value[dictCode].length > 0) return
    // 防止重复请求
    if (!requestQueue[dictCode]) {
      requestQueue[dictCode] = getDictItemList(dictCode).then((data: any) => {
        cacheDictItems(dictCode, data.data as ItemFormInt[])
        Reflect.deleteProperty(requestQueue, dictCode)
      })
    }
    await requestQueue[dictCode]
    return dictCache.value[dictCode]
  }

  /**
   * 获取字典项列表
   * @param dictCode 字典编码
   * @returns 字典项列表
   */
  const getDictItems = (dictCode: string): Promise<ItemFormInt[]> => {
    if (dictCache.value[dictCode] && dictCache.value[dictCode].length > 0) {
      return new Promise(resolve => {
        resolve(dictCache.value[dictCode])
      })
    } else {
      return loadDictItems(dictCode) as Promise<ItemFormInt[]>
    }
  }

  /**
   * 移除指定字典项
   * @param dictCode 字典编码
   */
  const removeDictItem = (dictCode: string) => {
    if (dictCache.value[dictCode]) {
      Reflect.deleteProperty(dictCache.value, dictCode)
    }
  }

  /**
   * 清空字典缓存
   */
  const clearDictCache = () => {
    dictCache.value = {}
  }

  return {
    dictCache,
    loadDictItems,
    removeDictItem,
    clearDictCache,
    getDictItems
  }
},{
  persist: true
})
